<template>
  <div class="view-container">
    <div class="custom_comments">
      <div class="searchBar">
        <el-form ref="form" label-width="8em" :inline="true">
          <el-form-item label="用户ID">
            <el-input style="width: 325px;" placeholder="请输入用户ID"
                      v-model="queryUserId"></el-input>
          </el-form-item>
          <el-form-item label="交易时间">
            <el-date-picker style="width: 325px;"
                            v-model="queryTime"
                            type="datetimerange"
                            :picker-options="pickerOptions2"
                            placeholder="选择时间范围"
                            align="right">
            </el-date-picker>
          </el-form-item>
          <br/>
          <el-form-item label="用户名">
            <el-input style="width: 325px;" placeholder="请输入用户名"
                      v-model="queryUserName"></el-input>
          </el-form-item>
          <br>

          <el-form-item class="editBtn">
            <el-button @click="getCommentsList" type="primary">搜索</el-button>
            <el-button @click="clearDate">重置
            </el-button>
          </el-form-item>
        </el-form>
      </div>
      <Empty v-if="commentsList.length==0">没有新消息
      </Empty>
      <div class="searchResult" v-if="commentsList.length!==0" v-loading="loading">
        <span>已选中 <i style="font-style: normal;color: red;">{{num}}</i>项 </span>
        <el-dropdown @command="handleCommand">
          <el-button type="primary">
            批量操作<i class="el-icon-caret-bottom el-icon--right"></i>
          </el-button>
          <el-dropdown-menu slot="dropdown">
            <el-dropdown-item>批量回复</el-dropdown-item>
          </el-dropdown-menu>
        </el-dropdown>
        <div v-if="batchReply" class="batchReply">
          <p>批量回复</p>
          <el-input v-model="getBatchComment" type="textarea"
                    :rows="2" resize="none"></el-input>
          <div style="text-align: right; margin: 0">
            <el-button size="mini" type="text" @click="batchReply = false">取消</el-button>
            <el-button type="primary" size="mini" @click="commitBatchComent">确定</el-button>
          </div>
        </div>
        <el-table
            ref="multipleTable"
            :data="commentsList"
            border
            tooltip-effect="dark"
            style="min-width: 1078px;margin: 20px 0"
            @selection-change="handleSelectionChange">
          <el-table-column
              type="selection"
              width="55">
          </el-table-column>
          <el-table-column
              label="用户ID"
              prop="userId" width="80">
          </el-table-column>
          <el-table-column
              prop="userName"
              label="用户名" width="120">
          </el-table-column>
          <el-table-column
              prop="orderId"
              label="关联订单"
              width="120">
          </el-table-column>
          <el-table-column
              prop="goodsName"
              label="关联商品名称">
          </el-table-column>
          <el-table-column
              prop="content"
              label="评论内容">
          </el-table-column>
          <el-table-column
              label="评论时间">
            <template slot-scope="scope">
              {{scope.row.commentTime | parseTime}}
            </template>
          </el-table-column>
          <el-table-column label="操作">
            <template slot-scope="scope">

              <el-popover
                  placement="left"
                  width="500"
                  trigger="click">
                <el-button v-if="scope.row.replyContent==''" size="small" type="primary" slot="reference" @click.stop.prevent="getCommentDetail(scope.row.id)" style="margin-right: 10px;">回复</el-button>
                <el-button v-if="scope.row.replyContent!=''" size="small" slot="reference" @click.stop.prevent="getCommentDetail(scope.row.id)" style="margin-right: 10px;">查看</el-button>

                <div class="comment-detail-wp" v-loading="loading2" element-loading-text="加载中">
                  <h3>评论详情</h3>
                  <div class="detail-form">
                    <el-form label-width="80px">
                      <el-form-item label="关联订单">
                        <span>{{ scope.row.orderNumber}}</span>
                      </el-form-item>
                      <el-form-item label="商品名称">
                        <span>{{ scope.row.goodsName }}</span>
                      </el-form-item>
                      <el-form-item label="商品规格">
                        <span>{{parsedStandard}}</span>
                      </el-form-item>
                      <el-form-item label="租金">
                        <span>￥{{commentData.rent | parsePrice}}</span>
                      </el-form-item>
                      <el-form-item label="评分">
                        <el-rate
                            style="padding-top: 6px;"
                            v-model="scope.row.score"
                            disabled
                            show-text
                            text-color="#ff9900"
                            text-template="{value}">
                        </el-rate>
                      </el-form-item>
                      <el-form-item label="评论内容">
                        <span>{{ scope.row.content }}</span>
                      </el-form-item>
                      <el-form-item label="图片">
                        <img :src="processImg(item.url)" alt="" v-for="(item,index) in commentImgs"
                             style="margin-right: 14px;"
                             @click.stop.prevent="$refs['previews'].previewImg(index)">
                      </el-form-item>

                      <!--有评论，显示评论不让编辑-->
                      <el-form-item v-if="scope.row.replyContent!=''" label="回复评论">
                        <el-input v-model="scope.row.replyContent"
                                  type="textarea"
                                  :rows="2"
                                  resize="none"
                                  :disabled="true"
                                  style="width: 100%;"
                                  ></el-input>
                        <div class="comment-aside">
                          <el-button @click.stop.prevent="closePop()">关闭</el-button>
                        </div>
                      </el-form-item>

                      <!--没有评论，去评论-->
                      <el-form-item v-if="scope.row.replyContent==''" label="回复评论">
                        <el-input type="textarea"
                                  :rows="2"
                                  v-model="getComment"
                                  resize="none"
                                  style="width: 100%;"
                                  >
                        </el-input>
                        <div class="comment-aside">
                          <el-button @click.stop.prevent="closePop()">取消</el-button>
                          <el-button type="primary" @click.stop.prevent="commitComment(scope.row.id)">回复评论</el-button>
                        </div>
                      </el-form-item>
                    </el-form>
                  </div>

                </div>

              </el-popover>


              <el-button @click="gotoDetail(scope.row.orderNumber)" type="text">订单详情</el-button>

            </template>
          </el-table-column>
        </el-table>

        <div style="text-align: center;margin-top: 24px;">
          <el-pagination
              @size-change="handleSizeChange"
              @current-change="handleCurrentChange"
              :current-page.sync="currentPage"
              :page-sizes="[5, 10, 15, 20]"
              :page-size="pageSize"
              layout="total, sizes, prev, pager, next, jumper"
              :total="totalLists">
          </el-pagination>
        </div>

      </div>
    </div>
    <!--图片预览-->
    <preview-img ref="previews" :list="commentImgs"></preview-img>
  </div>
</template>

<script>
  import {commentsLists} from '@/api/usersComments';
  import {parseTime, timeToServer} from '@/utils/datetime';
  import {comment, getCommentsById, subComment} from '@/api/usersList';
  import Empty from '@/components/Empty';
  import {host, osshost} from '@/api/util/fetch';
  import {isIllegal} from '@/utils/validate';
  import {showMessage} from '@/utils/message';

  import previewImg from '@/components/previewImg';


  export default {
    name: 'customerComments',
    components: {
      'Empty': Empty,
      'preview-img':previewImg,
    },
    data()
    {
      return {
        visible: false,
        getBatchComment: '',
        batchReply: false,
        commentData: {},
        pageSize: 5,
        currentPage: 1,
        getComment: '',
        pickerOptions2: {
          shortcuts: [
            {
              text: '最近一个月',
              onClick(picker)
              {
                const end = new Date();
                const start = new Date();
                start.setTime(start.getTime() - 3600 * 1000 * 24 * 30);
                picker.$emit('pick', [start, end]);
              }
            }]
        },
        queryTime: [],
        queryUserId: '',
        queryUserName: '',
        curState: 'all',
        commentState: [
          {
            value: 'all',
            label: '全部'
          },
          {
            value: 'show',
            label: '未屏蔽'
          },
          {
            value: 'hide',
            label: '已屏蔽'
          }
        ],
        commentsList:
          [],
        totalLists: 0,
        num: 0,
        ids: [],
        labelPosition: 'right',
        loading:false, //评论加载状态
        sending:false, //防重复提交

        loading2:false, //弹窗加载
      }
    },
    computed: {
      parsedStandard()
      {
        let str = this.commentData.standard;
        if (str && str !== 'undefined' || str !== '[]')
        {
          try
          {
            let standard = JSON.parse(str) || [];
            let s = [];
            standard.forEach(item => {
              s.push(item.name || '');
            });

            return s.join('->');

          } catch (e)
          {
            //console.log(e);
            return '';
          }
        }
        return '';
      },
      commentImgs()
      {
        let imgStr = this.commentData.contentImgUrl;
        if (imgStr && imgStr !== 'undefined' || imgStr !== '[]')
        {
          try
          {
            let imgArr = JSON.parse(imgStr) || [];
            for (let item of imgArr)
            {
              item.url = osshost + item.url;
            }
            return imgArr;
          } catch (e)
          {
            //console.log(e);
            return [];
          }

        }

//                return JSON.parse(imgStr);
      }
    },
    mounted()
    {
      this.currentPage = 1;
      this.pageSize = 5;
      this.getCommentsList();
    },
    methods: {
      processImg(url)
      {
        if (url && url !== 'undefined')
        {
          return url + '?x-oss-process=image/resize,m_fixed,h_60,w_60';
        }

        return '';
      },
      handleSizeChange(val)
      {
//              每页条数 后台传参数直接获取渲染 当前的customerList
        this.pageSize = val;
        this.getCommentsList()
      },
      handleCurrentChange(val)
      {
//              当前页数
        this.currentPage = val;
        this.getCommentsList();
      },
      handleSelectionChange(val)
      {
        this.num = val.length;
        let arr = [];
        for (let item of val)
        {
          if (item.replyContent)
          {
//                        已经存在评论
            this.$message.error('评论已回复！');

          } else
          {
            arr.push(item.id)
          }

        }
        this.ids = arr;
      },
      handleCommand()
      {
//                批量回复
        if (this.ids.length === 0)
        {
          this.$message({
            type: 'warning',
            message: '您还没有选择要回复的商品'
          });
        } else
        {
          this.batchReply = true;
        }

      },
      getCommentsList()
      {
        this.loading = true;
        let data = {
          userId: this.queryUserId,
          userName: this.queryUserName,
          pageNum: this.currentPage,
          pageSize: this.pageSize,

        };
        if (this.queryTime.length !== 0)
        {
          data.startCommentTime = timeToServer(this.queryTime[0]);
          data.endCommentTime = timeToServer(this.queryTime[1]);
        }
        comment(data)
          .then((resp) => {
//                        console.log(resp);
            /*for (let item of resp.data.list) {
                item.commentTime = parseTime(item.commentTime / 1000);
            }*/
            this.commentsList = resp.data.list || [];
            this.totalLists = resp.data.total || 0;
            setTimeout(() => {
              this.loading = false;
            }, 300);
          }).catch((err) => {
          setTimeout(() => {
            this.loading = false;
          }, 300);
        })
      },
      clearDate()
      {
        this.queryTime = [];
        this.queryUserId = '';
        this.queryUserName = '';
        this.curState = '';
      },
      gotoDetail(orderId)
      {
        this.$router.push({name: 'orderInfo', query: {id: orderId}});
      },
      commitComment(id)
      {
        //防止重复提交
        if(this.sending)
        {
          return;
        }

        this.sending=true;

//            提交评论
        if (this.getComment)
        {
//                    存在
          let data =
            [{
              "id": id,
              "replyContent": this.getComment

            }];
          subComment(data)
            .then((resp) => {
              showMessage({
                type: 'success',
                title: '评论成功',
                message: ''
              });
              this.getCommentsList();
              this.visible = false;
              this.getComment = '';

              this.sending=false;
                this.closePop();

            }).catch((err) => {
            this.sending=false;
          })
        } else
        {
          this.$message.error('评论内容不能为空');
          return;
        }

      },
      commitBatchComent()
      {
        //防止重复提交
        if(this.sending)
        {
          return;
        }

        this.sending=true;

        let data = [];
        for (let item of this.ids)
        {
          let a = {
            "id": item,
            "replyContent": this.getBatchComment
          };
          data.push(a);
        }
//                console.log(data);
        subComment(data).then((resp) => {
//                    console.log(resp);
          this.batchReply = false;
          this.getCommentsList();
          this.sending=false;

        }).catch((err) => {
          this.sending=false;

        })
      },
      getCommentDetail(id) //获取评论详情
      {
        document.querySelector("#app").click();

        this.loading2 = true;

        let data = {
          id: id
        };
        getCommentsById(data)
          .then((resp) => {
            this.commentData = resp.data;
            this.loading2 = false;
            //this.visible = true;
          }).catch((err) => {
          this.loading2 = false;
        })
      },
      closePop() //关闭评论详情弹窗
      {
        document.querySelector("#app").click();
        this.getComment='';
      }
    }
  }
</script>

<style lang="less" scoped>
  .custom_comments {
    .searchBar {
      background: rgba(249, 249, 249, 1);
      padding: 24px;
      .editBtn {
        display: block;
        text-align: center;
        margin-top: 24px;
        .el-button {
          margin-left: 40px;
        }
      }
    }

    .searchResult {
      position: relative;
      .batchReply {
        padding: 24px;
        width: 400px;
        height: 250px;
        border: 1px solid #aaa;
        position: absolute;
        top: 50px;
        left: 200px;
        z-index: 999;
        background: #fff;
        > .el-textarea {
          margin: 10px 0;
          > textarea {
            min-height: 100px;
          }
        }
      }

    }
  }

  .comment-detail-wp
  {
    padding: 5px 15px 5px 5px;
    max-height: 600px;
    overflow: auto;

    h3
    {
      text-align: center;
    }

    .detail-form
    {
      .el-form-item
      {
        margin-bottom: 10px;

      }

      .comment-aside
      {
        margin: 15px 0;
        text-align: right;
      }
    }
  }

</style>
